package com.xujianlun.cpms.controller.sys;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xujianlun.cpms.common.*;
import com.xujianlun.cpms.common.Response;
import com.xujianlun.cpms.config.AuthAccess;
import com.xujianlun.cpms.dto.UserDto;
import com.xujianlun.cpms.dto.UserPassWordDto;
import com.xujianlun.cpms.dto.ValidationEmailDto;
import com.xujianlun.cpms.entity.sys.Validation;
import com.xujianlun.cpms.exception.ServiceException;
import com.xujianlun.cpms.service.sys.EmailService;
import com.xujianlun.cpms.service.sys.IValidationService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import com.xujianlun.cpms.service.sys.IUserService;
import com.xujianlun.cpms.entity.sys.User;


import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author xujianlun
 * @since 2022-11-14
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;
    @Resource
    private EmailService emailService;
    @Resource
    private IValidationService validationService;
    @PostMapping
    public Response save(@RequestBody User user) {
        return Response.success(userService.saveOrUpdate(user));
    }

    @PostMapping("/login")
    public Response login(@RequestBody UserDto userDto) {
        String username = userDto.getUserName();
        String password = userDto.getPassWord();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Response.error("参数错误");
        }
        UserDto dto = userService.login(userDto);

        return Response.success(dto);
    }

    @PostMapping("/register")
    public Response register(@RequestBody UserDto userDto) {
        String username = userDto.getUserName();
        String password = userDto.getPassWord();
        String email = userDto.getEmail();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password) || StrUtil.isBlank(email)) {
            return Response.error("参数错误");
        }
        String Role="ROLE_USER";//新用户注册默认角色
        userDto.setRole(Role);
        return Response.success(userService.register(userDto));
    }

    @PostMapping("/rePassWord")
    public Response rePassWord(@RequestBody UserPassWordDto userPassWordDto) {
        userService.updatePassword(userPassWordDto);
        return Response.success();
    }
    @AuthAccess
    @GetMapping("/sendEmail")
    public Response sendEmailCode(@RequestParam String email,@RequestParam String userName) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_name",userName);
        userQueryWrapper.eq("email",email);
        User user = userService.getOne(userQueryWrapper);
        if (user ==null){
            throw new ServiceException(10005,"当前用户不存在或者绑定邮箱错误");
        }
        emailService.sendEmailCode(email, user.getNickName());
        return Response.success();
    }
    @AuthAccess
    @Transactional
    @PostMapping("/validationEmail")
    public Response validationCode(@RequestBody ValidationEmailDto validationEmailDto) {
        if (validationEmailDto==null){
            throw new ServiceException(10005,"您的验证码，邮箱，账号可能输入有误或者未输入");
        }
        String code = validationEmailDto.getCode();
        String email = validationEmailDto.getEmail();
        String userName = validationEmailDto.getUserName();
        String passWord = validationEmailDto.getNewPassWord();
        Date now = new Date();
        QueryWrapper<Validation> validationQueryWrapper = new QueryWrapper<>();
        validationQueryWrapper.eq("code",code);
        validationQueryWrapper.eq("type", ValidationEnum.FORGET_PASSWORD.getCode());
        validationQueryWrapper.ge("time",now);//查询数据库没过期的code
        validationQueryWrapper.eq("email",email);
        Validation one = validationService.getOne(validationQueryWrapper);
        if (one ==null){
            throw new ServiceException(10005,"当前验证码已经过期或与邮箱不匹配，请检查验证码进行验证");
        }
        QueryWrapper<User> w = new QueryWrapper<>();
        w.eq("user_name",userName);
        w.eq("email",email);
        User user = userService.getOne(w);
        if (user ==null){
            throw new ServiceException(10006,"用户以及邮箱校验失败，请重新试！");
        }
        userService.updatePasswordByEmailUserName(email,passWord,userName);
        return Response.success();
    }
    @GetMapping("/username/{username}")
    public Response findByUserName(@PathVariable String username) {
        QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("user_name", username);
        return Response.success(userService.getOne(objectQueryWrapper));
    }

    @DeleteMapping("/{id}")
    public Response delete(@PathVariable Integer id) {
        User user = userService.getById(id);
        if ("ROLE_ADMIN".equals(user.getRole())){
            throw new ServiceException(-200,"不可删除超级管理员角色");
        }
        return Response.success(userService.removeById(id));
    }

    @PostMapping("/batch/")
    public Response deleteBatch(@RequestBody List<Integer> ids) {
        for (Integer id:ids){
            User user = userService.getById(id);
            if ("ROLE_ADMIN".equals(user.getRole())){
                throw new ServiceException(-200,"不可删除超级管理员角色");
            }
        }
        return Response.success(userService.removeByIds(ids));
    }

    @GetMapping
    public Response findAll() {
        return Response.success(userService.list());
    }

    @GetMapping("/{id}")
    public Response findOne(@PathVariable Integer id) {
        return Response.success(userService.getById(id));
    }

    /**
     * 查询所有用户
     * @param pageNum
     * @param pageSize
     * @param nickName
     * @param phone
     * @param address
     * @return
     */
    @GetMapping("/page")
    public Response findPage(@RequestParam Integer pageNum,
                             @RequestParam Integer pageSize,
                             @RequestParam(defaultValue = "") String nickName,
                             @RequestParam(defaultValue = "") String phone,
                             @RequestParam(defaultValue = "") String address) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (!"".equals(nickName)) {
            queryWrapper.like("nick_name", nickName);
        }
        if (!"".equals(phone)) {
            queryWrapper.like("phone", phone);
        }
        if (!"".equals(address)) {
            queryWrapper.like("address", address);
        }
        //倒叙
        queryWrapper.orderByDesc("id");
        return Response.success(userService.page(page, queryWrapper));
    }

    /**
     * 学校区域类别
     * @param pageNum
     * @param pageSize
     * @param nickName
     * @param phone
     * @param address
     * @return
     */
    @GetMapping("/schoolPage")
    public Response findSchoolPage(@RequestParam Integer pageNum,
                             @RequestParam Integer pageSize,
                             @RequestParam(defaultValue = "") String nickName,
                             @RequestParam(defaultValue = "") String phone,
                                   @RequestParam(defaultValue = "") String localName,
                             @RequestParam(defaultValue = "") String address) {
        String local="学校";
        return Response.success(userService.getSchoolPage(new Page<>(pageNum, pageSize),nickName,phone,address,local,localName));
    }

    @PostMapping("/schoolDelete/{id}")
    public  Response deleteStudent(@PathVariable Integer id){
        //清空
        String local = "";
        String localName = "";
        User userServiceById = userService.getById(id);
        userServiceById.setLocale(local);
        userServiceById.setLocalName(localName);
        userService.updateById(userServiceById);
        return Response.success();
    }
    @PostMapping("/batch/schoolDelete/")
    public Response batchSchoolDelete(@RequestBody List<Integer> ids){
        //清空
        String local = "";
        for (Integer id:ids){
            User userServiceById = userService.getById(id);
            userServiceById.setLocale(local);
            userService.updateById(userServiceById);
        }
        return Response.success();
    }

    /**
     * 0企业信息接口查询
     * @param pageNum
     * @param pageSize
     * @param nickName
     * @param phone
     * @param address
     * @return
     */
    @GetMapping("/companyPage")
    public Response findCompanyPage(@RequestParam Integer pageNum,
                                   @RequestParam Integer pageSize,
                                   @RequestParam(defaultValue = "") String nickName,
                                   @RequestParam(defaultValue = "") String phone,
                                    @RequestParam(defaultValue = "") String localName,
                                   @RequestParam(defaultValue = "") String address) {
        String local="企业";
        return Response.success(userService.getSchoolPage(new Page<>(pageNum, pageSize),nickName,phone,address,local,localName));
    }

    /**
     * 社区信息查询
     * @param pageNum
     * @param pageSize
     * @param nickName
     * @param phone
     * @param address
     * @return
     */
    @GetMapping("/communityPage")
    public Response findCommunityPage(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(defaultValue = "") String nickName,
                                    @RequestParam(defaultValue = "") String phone,
                                      @RequestParam(defaultValue = "") String localName,
                                    @RequestParam(defaultValue = "") String address) {
        String local="社区";
        return Response.success(userService.getSchoolPage(new Page<>(pageNum, pageSize),nickName,phone,address,local,localName));
    }
}

